package com.clps.rulesregulations.controller;

import com.clps.rulesregulations.domain.*;
import com.clps.rulesregulations.service.RegulationService;
import com.clps.rulesregulations.service.UserService;
import com.clps.rulesregulations.util.*;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.springframework.util.StringUtils.replace;

/**
 * 制度管理
 *
 * @author zhangchao
 * @date 2018-10-08
 */
@Controller
@RequestMapping(value = "/regulation")
public class RegulationController {
    @Autowired
    private UserService userService;

    @Autowired
    private RegulationService regulationService;

    @Value("${file.url.path}")
    private String file_path;

    @Value("${local.path}")
    private String local_path;

    /**
     * 进入菜单管理页面
     *
     * @return
     */
    @GetMapping("/createmenu")
    public String login() {
        return "regulation/createmenu";
    }

    /**
     * 查询所有规章制度目录
     *
     * @return
     */
    @GetMapping("/data")
    @ResponseBody
    public ResultView data() {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        //查询所有规章制度目录
        List<ResourceTree> regulations = regulationService.findDirAsTree();
        if (regulations != null & !regulations.isEmpty()) {
            if (regulations.size() == 1) {

            } else {
                regulations = regulations.get(0).getChildren();
            }
        }
        //查询该角色所有资源ID
        List<Integer> regulationIds = regulationService.findDirRegulationIds();
        Map<String, Object> map = new HashMap<>();
        map.put("regulations", regulations);
        map.put("regulationIds", regulationIds);
        resultView.setValue(map);
        return resultView;
    }

    /**
     * 查询所有规章制度目录
     *
     * @return
     */
    @GetMapping("/dataAll")
    @ResponseBody
    public ResultView dataAll() {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        //查询所有规章制度目录
        List<ResourceTree> regulations = regulationService.findAllDirAsTree();
        if (regulations != null & !regulations.isEmpty()) {
            if (regulations.size() == 1) {

            } else {
                regulations = regulations.get(0).getChildren();
            }
        }
        //查询该角色所有资源ID
        List<Integer> regulationIds = regulationService.findAllDirRegulationIds();
        Map<String, Object> map = new HashMap<>();
        map.put("regulations", regulations);
        map.put("regulationIds", regulationIds);
        resultView.setValue(map);
        return resultView;
    }

    /**
     * 查询所有规章制度目录
     *
     * @return
     */
    @GetMapping("/dirfiledata")
    @ResponseBody
    public ResultView dirfiledata() {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        //查询所有规章制度目录
        List<ResourceTree> regulations = regulationService.findAllAsTree();
        if (regulations != null & !regulations.isEmpty()) {
            if (regulations.size() == 1) {

            } else {
                regulations = regulations.get(0).getChildren();
            }
        }
        //查询该角色所有资源ID
        List<Integer> regulationIds = regulationService.findAllRegulationIds();
        Map<String, Object> map = new HashMap<>();

        map.put("regulations", regulations);
        map.put("regulationIds", regulationIds);
        resultView.setValue(map);
        return resultView;
    }

    /**
     * 查询所有规章制度目录
     *
     * @return
     */
    @GetMapping("/showtreebyparentid")
    @ResponseBody
    public ResultView showtreebyparentid(String id, String parentId) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        //查询所有规章制度目录
        List<ResourceTree> regulations = regulationService.findAllAsTreeByParentId(id, parentId);
        if (regulations != null & !regulations.isEmpty()) {
            if (regulations.size() == 1) {

            } else {
                regulations = regulations.get(0).getChildren();
            }
        }

        Map<String, Object> map = new HashMap<>();

        map.put("regulations", regulations);

        resultView.setValue(map);
        return resultView;
    }

    /**
     * 进入所有规章制度页面
     *
     * @return
     */
    @GetMapping("/list")
    public String list() {
        return "regulation/list";
    }

    /**
     * 分页查询所有规章制度
     *
     * @param condition
     * @return
     */
    @PostMapping("/list")
    @ResponseBody
    public ResultView list(@RequestBody Map<String, Object> condition) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        PageInfo<Rule> rules = regulationService.findAllRules(condition);
        resultView.setValue(rules);
        return resultView;
    }

    /**
     * 进入规章历史版本页面
     *
     * @return
     */

    @GetMapping("/listversion/{id}")
    public String listversion(@PathVariable Integer id) {
        return "regulation/regulationhis";
    }

    /**
     * 进入规章历史版本页面
     *
     * @return
     */
    @GetMapping("/toRuleWatch/{id}")
    public String toRuleWatch(@PathVariable Integer id) {
        return "regulation/rulewatch";
    }

    /**
     * 分页查询规章历史版本
     *
     * @param condition
     * @return
     */
    @PostMapping("/listversion")
    @ResponseBody
    public ResultView listversion(@RequestBody Map<String, Object> condition) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        PageInfo<Rule> rules = regulationService.findAllRulesHis(condition);
        resultView.setValue(rules);
        return resultView;
    }

    /**
     * 分页查询规章历史版本
     *
     * @param condition
     * @return
     */
    @PostMapping("/schedule")
    @ResponseBody
    public ResultView schedule(@RequestBody Map<String, Object> condition) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        PageInfo<Schedule> rules = regulationService.findAllSchedules(condition);
        resultView.setValue(rules);
        return resultView;
    }

    /**
     * 分页查询规章历史版本
     *
     * @return
     */

    @PostMapping("/schedule/edit")
    @ResponseBody
    public ResultView scheduleEdit(@RequestParam(value = "id") String id,@RequestParam(value = "schedule") String schedule) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        regulationService.scheduleEdit(id,schedule);
        return resultView;
    }

    /**
     * 最新修改文件（更多）
     *
     * @param condition
     * @return
     */
    @PostMapping("/showmoreeditfile")
    @ResponseBody
    public ResultView showmoreeditfile(@RequestBody Map<String, Object> condition) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        PageInfo<Rule> rules = regulationService.showmoreeditfile(condition);
        List list = rules.getList();

        resultView.setValue(rules);
        return resultView;
    }

    /**
     * 热搜文件（更多）
     *
     * @param condition
     * @return
     */
    @PostMapping("/showmorehotsearch")
    @ResponseBody
    public ResultView showmorehotsearch(@RequestBody Map<String, Object> condition) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        PageInfo<Rule> rules = regulationService.showmorehotsearch(condition);
        List list = rules.getList();

        resultView.setValue(rules);
        return resultView;
    }

    /**
     * 最新修改文件
     *
     * @param condition
     * @return
     */
    @PostMapping("/listLatestUpdFile")
    @ResponseBody
    public ResultView listLatestUpdFile(@RequestBody Map<String, Object> condition) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        PageInfo<Rule> rules = regulationService.listLatestUpdFile(condition);
        List list = rules.getList();
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                Rule rule = (Rule) list.get(i);

                if (rule.getTitle().length() > 20) {
                    rule.setTitle(rule.getTitle().substring(0, 20) + "..");
                }
            }
        }
        resultView.setValue(rules);
        resultView.setStatus(ResultView.SUCCESS);
        return resultView;
    }

    /**
     * 热搜文件
     *
     * @param condition
     * @return
     */
    @PostMapping("/listkeywordHot")
    @ResponseBody
    public ResultView listkeywordHot(@RequestBody Map<String, Object> condition) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        PageInfo<Rule> rules = regulationService.listkeywordHot(condition);
        List list = rules.getList();
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                Rule rule = (Rule) list.get(i);

                if (rule.getTitle().length() > 20) {
                    rule.setTitle(rule.getTitle().substring(0, 20) + "..");
                }
            }
        }
        resultView.setValue(rules);
        resultView.setStatus(ResultView.SUCCESS);
        return resultView;
    }

    /**
     * 编辑制度目录信息
     *
     * @return
     */
    @PostMapping("/confirm")
    @ResponseBody
    public ResultView confirm(@RequestBody List<Regulation> regulationsList) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        List<Regulation> addList = new ArrayList();
        List<Regulation> updateList = new ArrayList();
        List<Regulation> deleteList = new ArrayList();

        //整理到不同的list里
        if (regulationsList != null && regulationsList.size() > 0) {
            for (int i = 0; i < regulationsList.size(); i++) {
                Regulation rl = regulationsList.get(i);
                if (Const.INSERT.equals(rl.getFlag())) {
                    addList.add(rl);
                } else if (Const.UPDATE.equals(rl.getFlag())) {
                    updateList.add(rl);
                } else if (Const.DELETE.equals(rl.getFlag())) {
                    deleteList.add(rl);
                }
            }
        }
        List<String> existFileList = new ArrayList<>();
        List<String> existFileAndDirList = new ArrayList<>();
        List<String> getDelDirList = new ArrayList<>();

        Map<String, String> fileDirDelMap = new HashMap();
        List<String> fileDirDelList = new ArrayList<>();
        Map newDelRuleMap = new HashMap();
        List<Regulation> ruleDelMenuIdList = new ArrayList();
        if (deleteList.size() > 0) {
            for (int m = 0; m < deleteList.size(); m++) {
                Regulation delReg = deleteList.get(m);
                getDelDirList = regulationService.getDelDirList(delReg.getId());
                if (getDelDirList != null && getDelDirList.size() > 0) {
                    for (int k = 0; k < getDelDirList.size(); k++) {
                        String delId = getDelDirList.get(k);
                        newDelRuleMap.put(delId, delId);
                    }
                }

            }

            if (newDelRuleMap != null) {
                Iterator<Map.Entry<String, Object>> it = newDelRuleMap.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, Object> entry = it.next();
                    String key = entry.getKey();
                    Regulation rl = new Regulation();
                    rl.setId(Integer.valueOf(key));
                    ruleDelMenuIdList.add(rl);
                }
            }

            //删除rule表做准备
            existFileList = regulationService.selectFileExistCount(ruleDelMenuIdList);

            //获得所有子目录和文件id
            for (int m = 0; m < deleteList.size(); m++) {
                Regulation delReg = deleteList.get(m);
                existFileAndDirList = regulationService.selectFileDirExistCount(String.valueOf(delReg.getId()));
                for (int n = 0; n < existFileAndDirList.size(); n++) {
                    String rt = existFileAndDirList.get(n);
                    fileDirDelMap.put(rt, rt);
                }
            }

            if (fileDirDelMap != null) {
                for (String key : fileDirDelMap.keySet()) {
                    fileDirDelList.add(key);
                }
            }
        }

        //对目录和文件做增刪改操作
        regulationService.saveFileAndDir(addList, updateList, fileDirDelList, existFileList);

        resultView.setStatus(ResultView.SUCCESS);
        return resultView;
    }

    /**
     * 删除文件
     *
     * @return
     */
    @PostMapping("/deleteFile")
    @ResponseBody
    public ResultView deleteFile(@RequestBody Map<String, Object> condition) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);

        regulationService.deleteFile(condition);

        resultView.setStatus(ResultView.SUCCESS);
        return resultView;
    }

    /**
     * 编辑制度目录信息
     *
     * @return
     */
    @PostMapping("/deleteCatalog")
    @ResponseBody
    public ResultView deleteCatalog(@RequestBody Map<String, Object> condition) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);

        List<Regulation> deleteList = new ArrayList();

        Integer id = (Integer) condition.get("id");
        Regulation rr = new Regulation();
        rr.setId(id);
        deleteList.add(rr);

        List<String> existFileList = new ArrayList<>();
        List<String> existFileAndDirList = new ArrayList<>();
        List<String> getDelDirList = new ArrayList<>();

        Map<String, String> fileDirDelMap = new HashMap();
        List<String> fileDirDelList = new ArrayList<>();
        Map newDelRuleMap = new HashMap();
        List<Regulation> ruleDelMenuIdList = new ArrayList();
        if (deleteList.size() > 0) {
            for (int m = 0; m < deleteList.size(); m++) {
                Regulation delReg = deleteList.get(m);
                getDelDirList = regulationService.getDelDirList(delReg.getId());
                if (getDelDirList != null && getDelDirList.size() > 0) {
                    for (int k = 0; k < getDelDirList.size(); k++) {
                        String delId = getDelDirList.get(k);
                        newDelRuleMap.put(delId, delId);
                    }
                }

            }

            if (newDelRuleMap != null) {
                Iterator<Map.Entry<String, Object>> it = newDelRuleMap.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, Object> entry = it.next();
                    String key = entry.getKey();
                    Regulation rl = new Regulation();
                    rl.setId(Integer.valueOf(key));
                    ruleDelMenuIdList.add(rl);
                }
            }

            //删除rule表做准备
            existFileList = regulationService.selectFileExistCount(ruleDelMenuIdList);

            //获得所有子目录和文件id
            for (int m = 0; m < deleteList.size(); m++) {
                Regulation delReg = deleteList.get(m);
                existFileAndDirList = regulationService.selectFileDirExistCount(String.valueOf(delReg.getId()));
                for (int n = 0; n < existFileAndDirList.size(); n++) {
                    String rt = existFileAndDirList.get(n);
                    fileDirDelMap.put(rt, rt);
                }
            }

            if (fileDirDelMap != null) {
                for (String key : fileDirDelMap.keySet()) {
                    fileDirDelList.add(key);
                }
            }
        }

        //对目录和文件做增刪改操作
        regulationService.saveFileAndDir(new ArrayList<>(), new ArrayList<>(), fileDirDelList, existFileList);

        resultView.setStatus(ResultView.SUCCESS);
        return resultView;
    }

    /**
     * 编辑制度目录信息
     *
     * @return
     */
    @PostMapping("/edit")
    @ResponseBody
    public ResultView edit(@RequestBody List<Regulation> regulationsList) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);

        List<Regulation> deleteList = new ArrayList();

        if (regulationsList != null && regulationsList.size() > 0) {
            for (int i = 0; i < regulationsList.size(); i++) {
                Regulation rl = regulationsList.get(i);
               if (Const.DELETE.equals(rl.getFlag())) {
                    deleteList.add(rl);
                }
            }
        }
        List<String> existFileList = new ArrayList<>();
        if (deleteList.size() > 0) {
            existFileList = regulationService.selectFileExistCount(deleteList);

            if (existFileList != null && existFileList.size() > 0) {
                resultView.setStatus(ResultView.ERROR);
                resultView.setMsg("删除的目录中存在文件，无法删除，请重新操作");
                return resultView;
            }
        }
        resultView.setStatus(ResultView.SUCCESS);
        return resultView;
    }

    /**
     * 编辑制度目录信息
     *
     * @return
     */
    @PostMapping("/deleteConfirm")
    @ResponseBody
    public ResultView deleteConfirm(@RequestBody Map<String, Object> condition) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        List<Regulation> addList = new ArrayList();
        List<Regulation> updateList = new ArrayList();
        List<Regulation> deleteList = new ArrayList();

        Integer id = (Integer) condition.get("id");
        Regulation rl = new Regulation();
        rl.setId(id);
        deleteList.add(rl);

        List<String> existFileList = new ArrayList<>();
        if (deleteList.size() > 0) {
            existFileList = regulationService.selectFileExistCount(deleteList);

            if (existFileList != null && existFileList.size() > 0) {
                resultView.setStatus(ResultView.ERROR);
                resultView.setMsg("删除的目录中存在文件，无法删除，请重新操作");
                return resultView;
            }
        }
        resultView.setStatus(ResultView.SUCCESS);
        return resultView;
    }

    /**
     * 进入上传文档页面
     *
     * @return
     */
    @GetMapping("/uploadregulation")
    public String uploadregulation() {
        return "regulation/uploadregulation";
    }

    /**
     * 上传word文件
     *
     * @param multipartfiles
     * @param title
     * @param catalogId
     * @return
     * @throws Exception
     */
    @RequestMapping("/savesingle")
    @ResponseBody
    public ResultView savesingle(@RequestParam(value = "excelFile") MultipartFile[] multipartfiles, @RequestParam(value = "title") String title, @RequestParam(value = "catalogId") String catalogId) throws Exception {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        Map<String, Object> map = new HashMap<>();
        String content = "";
        //遍历文件
        if (multipartfiles != null && multipartfiles.length > 0) {
            for (MultipartFile item : multipartfiles) {

                String suffix = item.getOriginalFilename().substring(item.getOriginalFilename().lastIndexOf(".") + 1);

                String newFileName = Tools.getRandomFileName() + "." + suffix;//新文件名
                String upfileName = local_path + newFileName;

                File file1 = new File(upfileName);
                File fileParent = file1.getParentFile();
                //判断是否存在
                if (!fileParent.exists()) {
                    fileParent.mkdirs();//创建文件的目录
                }
                file1.createNewFile();//创建文件

                item.transferTo(file1);//拷贝

                List hrefList = new ArrayList();
                Elements links = null;
                if ("doc".equals(suffix)) {
                    content = WordToHtml.Word2003ToHtml(local_path, newFileName, file_path);
                    Document doc = (Document) Jsoup.parse(content);
                    links = doc.getElementsByTag("p");
                } else if ("docx".equals(suffix)) {
                    content = WordToHtml.Word2007ToHtml(file1, local_path, newFileName, file_path);
                }
            }
        }
        content = Base64Util.encode(content);
        resultView.setStatus(ResultView.SUCCESS);
        map.put("content", content);
        resultView.setValue(map);
        return resultView;
    }

    /**
     * 上传word文件
     *
     * @param multipartfiles
     * @param title
     * @return
     * @throws Exception
     */
    @RequestMapping("/savesingleNew")
    @ResponseBody
    public ResultView savesingleNew(@RequestParam(value = "excelFile") MultipartFile[] multipartfiles, @RequestParam(value = "title") String title) throws Exception {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        Map<String, Object> map = new HashMap<>();
        String content = "";
        //遍历文件
        if (multipartfiles != null && multipartfiles.length > 0) {
            for (MultipartFile item : multipartfiles) {

                String suffix = item.getOriginalFilename().substring(item.getOriginalFilename().lastIndexOf(".") + 1);

                String newFileName = Tools.getRandomFileName() + "." + suffix;//新文件名
                String upfileName = local_path + newFileName;

                File file1 = new File(upfileName);
                File fileParent = file1.getParentFile();
                //判断是否存在
                if (!fileParent.exists()) {
                    fileParent.mkdirs();//创建文件的目录
                }
                file1.createNewFile();//创建文件

                item.transferTo(file1);//拷贝

                List hrefList = new ArrayList();
                Elements links = null;
                if ("doc".equals(suffix)) {
                    content = WordToHtml.Word2003ToHtml(local_path, newFileName, file_path);
                    Document doc = (Document) Jsoup.parse(content);
                    links = doc.getElementsByTag("p");
                } else if ("docx".equals(suffix)) {
                    content = WordToHtml.Word2007ToHtml(file1, local_path, newFileName, file_path);
                }
            }
        }
        content = Base64Util.encode(content);
        resultView.setStatus(ResultView.SUCCESS);
        map.put("content", content);
        resultView.setValue(map);
        return resultView;
    }

    public static boolean isInteger(String str) {
        if (StringUtils.isEmpty(str)) {
            return false;
        }
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    /**
     * 上传word文件
     *
     * @param multipartfiles
     * @param title
     * @param catalogId
     * @return
     * @throws Exception
     */
    @RequestMapping("/save")
    @ResponseBody
    public ResultView save(@RequestParam(value = "excelFile") MultipartFile[] multipartfiles, @RequestParam(value = "title") String title, @RequestParam(value = "catalogId") String catalogId) throws Exception {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        Map<String, Object> map = new HashMap<>();
        String content = "";
        //遍历文件
        if (multipartfiles != null && multipartfiles.length > 0) {
            for (MultipartFile item : multipartfiles) {

                String suffix = item.getOriginalFilename().substring(item.getOriginalFilename().lastIndexOf(".") + 1);

                String newFileName = Tools.getRandomFileName() + "." + suffix;//新文件名
                String upfileName = local_path + newFileName;

                File file1 = new File(upfileName);
                File fileParent = file1.getParentFile();
                //判断是否存在
                if (!fileParent.exists()) {
                    fileParent.mkdirs();//创建文件的目录
                }
                file1.createNewFile();//创建文件

                item.transferTo(file1);//拷贝
                if ("doc".equals(suffix)) {

                    resultView.setStatus(ResultView.ERROR);
                    resultView.setMsg("目录文档上传暂不支持doc格式！");
                    return resultView;
//                    content = WordToHtml.Word2003ToHtml(local_path, newFileName, file_path);

                } else if ("docx".equals(suffix)) {
                    content = WordToHtml.Word2007ToHtml(file1, local_path, newFileName, file_path);

                }

                Document doc = (Document) Jsoup.parse(content);

                Elements links = doc.getElementsByTag("p");
                if (links != null) {
                    if (links.toString().indexOf("_Toc") == -1) {
                        resultView.setStatus(ResultView.ERROR);
                        resultView.setMsg("请上传带有目录格式的文件！");
                        return resultView;
                    }
                }

//                    regulationService.detailDocx(doc, catalogId);
                String str = regulationService.detailDocxByStyle(doc, catalogId, upfileName);
                if (!StringUtils.isEmpty(str)) {
                    resultView.setStatus(ResultView.ERROR);
                    resultView.setMsg(str);
                    return resultView;
                }
            }
        }
        resultView.setStatus(ResultView.SUCCESS);
        map.put("content", content);
        resultView.setValue(map);
        return resultView;
    }

    /**
     * 判断字符串中是否包含中文
     *
     * @param str 待校验字符串
     * @return 是否为中文
     * @warn 不能校验是否为中文标点符号
     */
    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    /**
     * 上传附件
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/savefile")
    @ResponseBody
    public ResultView savefile(HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<>();
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
        List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                .getFiles("excelFileExtra");

        String fileUrl = "";
        String fileName = "";
        String fileId = "";
        if (files != null) {
            for (int i = 0; i < files.size(); i++) {
                MultipartFile item = files.get(i);
                String suffix = item.getOriginalFilename().substring(item.getOriginalFilename().lastIndexOf(".") + 1);

                fileName = item.getOriginalFilename();
                String newFileName = Tools.getRandomFileName() + "." + suffix;//新文件名
                String upfileName = local_path + newFileName;

                File file1 = new File(upfileName);
                File fileParent = file1.getParentFile();
                //判断是否存在
                if (!fileParent.exists()) {
                    fileParent.mkdirs();//创建文件的目录
                }
                file1.createNewFile();//创建文件

                item.transferTo(file1);//拷贝

                fileUrl = file_path + newFileName;

                fileId = CommonUtil.getUuid();
            }
        }

        map.put("fileUrl", fileUrl);
        map.put("fileName", fileName);
        map.put("fileId", fileId);
        resultView.setValue(map);
        return resultView;
    }
    /**
     * 上传附件
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/delFile")
    @ResponseBody
    public ResultView delFile(HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<>();
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        RuleFilelist rf = new RuleFilelist();
        String oldid = request.getParameter("oldId");
        rf.setId(oldid);//主键
        regulationService.delFile(rf);

        resultView.setValue(map);
        return resultView;
    }
    /**
     * 上传附件
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/updatefile")
    @ResponseBody
    public ResultView updatefile(HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<>();
        ResultView resultView = new ResultView(ResultView.SUCCESS);

        MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
        List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                .getFiles("excelFileExtraUpd");

        String fileUrl = "";
        String fileName = "";
        String fileId = "";
        if (files != null) {
            for (int i = 0; i < files.size(); i++) {
                MultipartFile item = files.get(i);
                String suffix = item.getOriginalFilename().substring(item.getOriginalFilename().lastIndexOf(".") + 1);

                fileName = item.getOriginalFilename();
                String newFileName = Tools.getRandomFileName() + "." + suffix;//新文件名
                String upfileName = local_path + newFileName;

                File file1 = new File(upfileName);
                File fileParent = file1.getParentFile();
                //判断是否存在
                if (!fileParent.exists()) {
                    fileParent.mkdirs();//创建文件的目录
                }
                file1.createNewFile();//创建文件

                item.transferTo(file1);//拷贝

                fileUrl = file_path + newFileName;

                fileId = CommonUtil.getUuid();

                RuleFilelist rf = new RuleFilelist();
                String id = request.getParameter("fileId");
                String oldid = request.getParameter("oldId");
                rf.setId(oldid);//主键
                rf.setFileId(id);
                rf.setCreateTime(new Date());
                rf.setUploadOriginname(item.getOriginalFilename());
                rf.setUploadRealname(newFileName);
                rf.setSuffix(suffix);
                Session session = SecurityUtils.getSubject().getSession();
                User u = (User) session.getAttribute("userSession");
                rf.setUpdateTime(new Date());
                rf.setUpdator(String.valueOf(u.getId()));
                regulationService.updateFile(rf);
//                regulationService.saveFile(rf);
//                rf.setFileId();
            }
        }

        map.put("fileUrl", fileUrl);
        map.put("fileName", fileName);
        map.put("fileId", fileId);

        resultView.setValue(map);
        return resultView;
    }

    /**
     * 上传附件
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/saveNewfile")
    @ResponseBody
    public ResultView saveNewfile(HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<>();
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
        List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                .getFiles("excelFileExtra");

        String fileUrl = "";
        String fileName = "";
        String fileId = "";
        if (files != null) {
            for (int i = 0; i < files.size(); i++) {
                MultipartFile item = files.get(i);
                String suffix = item.getOriginalFilename().substring(item.getOriginalFilename().lastIndexOf(".") + 1);

                fileName = item.getOriginalFilename();
                String newFileName = Tools.getRandomFileName() + "." + suffix;//新文件名
                String upfileName = local_path + newFileName;

                File file1 = new File(upfileName);
                File fileParent = file1.getParentFile();
                //判断是否存在
                if (!fileParent.exists()) {
                    fileParent.mkdirs();//创建文件的目录
                }
                file1.createNewFile();//创建文件

                item.transferTo(file1);//拷贝

                fileUrl = file_path + newFileName;

                fileId = CommonUtil.getUuid();

                RuleFilelist rf = new RuleFilelist();
                String id = request.getParameter("fileId");
                rf.setId(fileId);//主键
                rf.setFileId(id);
                rf.setCreateTime(new Date());
                rf.setUploadOriginname(item.getOriginalFilename());
                rf.setUploadRealname(newFileName);
                rf.setSuffix(suffix);

                regulationService.saveFile(rf);
//                rf.setFileId();
            }
        }

        map.put("fileUrl", fileUrl);
        map.put("fileName", fileName);
        map.put("fileId", fileId);
        resultView.setValue(map);
        return resultView;
    }

    /**
     * 保存word文档
     *
     * @param title
     * @param catalogId
     * @param content
     * @return
     * @throws Exception
     */
    @RequestMapping("/saveword")
    @ResponseBody
    public ResultView saveword(@RequestParam(value = "title") String title, @RequestParam(value = "catalogId") String catalogId,
                               @RequestParam(value = "content") String content) throws Exception {

        ResultView resultView = new ResultView(ResultView.SUCCESS);

        boolean bool = regulationService.saveword(title, catalogId, content);

        if (!bool) {
            resultView.setStatus(ResultView.ERROR);
            resultView.setMsg("标题在所选目录中已存在");
            return resultView;
        }
        resultView.setStatus(ResultView.SUCCESS);
        return resultView;
    }

    public String readToString(String fileName) {
        String encoding = "UTF-8";
        File file = new File(fileName);
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            return new String(filecontent, encoding);
        } catch (UnsupportedEncodingException e) {
            System.err.println("The OS does not support " + encoding);
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 编辑制度目录信息
     *
     * @return
     */
    @GetMapping("/showrule")
    @ResponseBody
    public ResultView showrule(@RequestParam String ruleId) {

        ResultView resultView = new ResultView(ResultView.SUCCESS);
        Rule rule = regulationService.selectRule(ruleId);
        Map<String, Object> map = new HashMap<>();
        map.put("rule", rule);

        rule.setContent(rule.getContent());

        //访问记录
        AccessFile af = new AccessFile();
        Session session = SecurityUtils.getSubject().getSession();
        User u = (User) session.getAttribute("userSession");
        af.setUsername(u.getUsername());
        af.setId(CommonUtil.getUuid());
        af.setAccessTime(new Date());
        af.setFileId(ruleId);
        regulationService.insertAccessTalbe(af);

        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.hasRole("管理员")) {
            map.put("hasrole", "1");
        }

        List<RuleFilelist> ruleFilelists = regulationService.getFileList(ruleId);
        if(ruleFilelists!=null && ruleFilelists.size()>0){
            for(int i=0;i<ruleFilelists.size();i++){
                RuleFilelist rfl = ruleFilelists.get(i);
                rfl.setFileName(getFileNameWithoutSuffix(rfl.getFileName()));
                rfl.setDownloadAddress(file_path+rfl.getUploadRealname());
            }
        }
        map.put("ruleFilelists", ruleFilelists);
        resultView.setValue(map);
        return resultView;
    }

    //获取不带后缀名的文件名
    public static String getFileNameWithoutSuffix(String file_name){
        if(file_name.indexOf(".")==-1){
            return file_name;
        }
        return file_name.substring(0, file_name.lastIndexOf("."));
    }

    @GetMapping("/showrulebykeyword")
    @ResponseBody
    public ResultView showrulebykeyword(@RequestParam String ruleId) {

        ResultView resultView = new ResultView(ResultView.SUCCESS);
        Rule rule = regulationService.selectRule(ruleId);
        Map<String, Object> map = new HashMap<>();
        map.put("rule", rule);

        rule.setContent(rule.getContent());

        resultView.setValue(map);
        return resultView;
    }

    /**
     * 编辑制度目录信息
     *
     * @return
     */
    @PostMapping("/addCatalog")
    @ResponseBody
    public ResultView addCatalog(@RequestBody Map<String, Object> condition) throws IOException {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        Map<String, Object> map = new HashMap<>();

        regulationService.addCatalog(condition);
        resultView.setValue(map);
        return resultView;
    }

    /**
     * 编辑制度目录信息
     *
     * @return
     */
    @PostMapping("/updateCatalog")
    @ResponseBody
    public ResultView updateCatalog(@RequestBody Map<String, Object> condition) throws IOException {
        ResultView resultView = new ResultView(ResultView.SUCCESS);
        Map<String, Object> map = new HashMap<>();

        regulationService.updateCatalog(condition);
        resultView.setValue(map);
        return resultView;
    }

    /**
     * 编辑制度目录信息
     *
     * @return
     */
    @PostMapping("/showupditem")
    @ResponseBody
    public ResultView showupditem(@RequestBody Map<String, Object> condition) throws IOException {

        String fileId = (String) (condition.get("fileId"));

        ResultView resultView = new ResultView(ResultView.SUCCESS);
        Map<String, Object> map = new HashMap<>();
        Rule rule = regulationService.selectRule(fileId);
        if (rule != null && rule.getStartTime() != null) {
            map.put("flag", "2");
        } else {
            map.put("flag", "1");
        }

        //会议参与人员
        List attendusersList = new ArrayList();
        String attendUser = rule.getAttendUser();
        if (!StringUtils.isEmpty(attendUser)) {
            attendUser = attendUser.substring(1, attendUser.length() - 1);
            String[] users = attendUser.split(",");
            for (int i = 0; i < users.length; i++) {

                String userid = users[i];
                User u = userService.findUserByUserId(Integer.valueOf(userid));
                attendusersList.add(u);
            }
        }

        rule.setAttendusersList(attendusersList);

        Date startTime = rule.getStartTime();
        if (startTime != null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr = simpleDateFormat.format(startTime);
            rule.setStartTimeShow(dateStr);
        }

        Date endTime = rule.getEndTime();
        if (endTime != null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr = simpleDateFormat.format(endTime);
            rule.setEndTimeShow(dateStr);
        }
        map.put("rule", rule);
        resultView.setValue(map);
        return resultView;
    }

    /**
     * 查询会议室列表
     *
     * @param condition
     * @return
     */
    @PostMapping("/searchAttendUsers")
    @ResponseBody
    public ResultView searchAttendUsers(@RequestBody Map<String, Object> condition) {
        ResultView resultView = new ResultView(ResultView.SUCCESS);

        String id = (String) condition.get("id");
        Rule rr = new Rule();
        rr = regulationService.selectRule(id);

        String attendUsers = rr.getAttendUser();
        if (!StringUtils.isEmpty(attendUsers)) {
            attendUsers = attendUsers.substring(1, attendUsers.length() - 1);
            String[] arr = attendUsers.split(",");
            List<String> attendUserList = Arrays.asList(arr);
            condition.put("list", attendUserList);
        } else {
            condition.put("list", new ArrayList<>());
        }

        PageInfo<User> users = userService.findUsersByList(condition);

        resultView.setValue(users);
        return resultView;
    }

    /**
     * 参与人员
     * @return
     */
    @PostMapping("/addAttendInfo")
    @ResponseBody
    public ResultView addAttendInfo(@RequestBody Rule rule) throws ParseException {
        ResultView resultView = new ResultView(ResultView.SUCCESS);

        regulationService.updateAttendInfo(rule);

        resultView.setStatus(ResultView.SUCCESS);
        return resultView;
    }


    /**
     * 编辑制度目录信息
     *
     * @return
     */
    @GetMapping("/showrulehis")
    @ResponseBody
    public ResultView showrulehis(@RequestParam String ruleId) {

        ResultView resultView = new ResultView(ResultView.SUCCESS);
        Rule rule = regulationService.selectRule(ruleId);

        Map<String, Object> map = new HashMap<>();

        map.put("rule", rule);

        rule.setContent(rule.getContent());

        resultView.setValue(map);
        return resultView;
    }

    /**
     * 编辑制度目录信息
     *
     * @return
     */
    @GetMapping("/revertregulation")
    @ResponseBody
    public ResultView revertregulation(@RequestParam String id) {

        ResultView resultView = new ResultView(ResultView.SUCCESS);

        regulationService.revertRule(id);

        Map<String, Object> map = new HashMap<>();
        map.put("success", Const.CONST_SUCCESS);
        resultView.setValue(map);
        return resultView;
    }

    /**
     * 统计热搜文件次数
     *
     * @return
     */
    @GetMapping("/fileclickcount")
    @ResponseBody
    public ResultView fileclickcount(@RequestParam String id) {

        regulationService.fileclickcount(id);

        ResultView resultView = new ResultView(ResultView.SUCCESS);

        Map<String, Object> map = new HashMap<>();
        map.put("success", Const.CONST_SUCCESS);
        resultView.setValue(map);
        return resultView;
    }


    /**
     * 编辑制度目录信息
     *
     * @return
     */
    @GetMapping("/deleteregulation")
    @ResponseBody
    public ResultView deleteregulation(@RequestParam String id) {

        ResultView resultView = new ResultView(ResultView.SUCCESS);
        Rule rule = regulationService.selectRuleHis(id);
        regulationService.deleteRuleHis(id);

        Map<String, Object> map = new HashMap<>();
        map.put("success", Const.CONST_SUCCESS);
        map.put("ruleid", rule.getRuleId());
        resultView.setValue(map);
        return resultView;
    }


    /**
     * 进入word编辑页
     *
     * @return
     */
    @GetMapping("/editregulation/{id}")
    public String editregulation(@PathVariable Integer id) {
        return "regulation/editregulation";
    }

    /**
     * 进入word详情页
     *
     * @return
     */
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable Integer id) throws IOException {
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("regulation", "9999");
        Rule rule = regulationService.selectRuleByMenuId(String.valueOf(id));
//        response.sendRedirect("/regulation/showregulation/" +rule.getId());
        return "redirect:/regulation/showregulation/" + rule.getId();

    }

    /**
     * 进入word详情页
     *
     * @return
     */
    @GetMapping("/detaildept/{keywordid}/{id}")
    public String detaildept(@PathVariable String keywordid, @PathVariable Integer id) throws IOException {
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("regulation", "8888");
        session.setAttribute("keywordid", keywordid);
        Rule rule = regulationService.selectRuleByMenuId(String.valueOf(id));
//        response.sendRedirect("/regulation/showregulation/" +rule.getId());
        return "redirect:/regulation/showregulation/" + rule.getId();

    }

    /**
     * 进入word详情页
     *
     * @return
     */
    @GetMapping("/showregulation/{id}")
    public String showregulation(Integer id) {
        return "regulation/showregulation";
    }

    /**
     * 进入word详情页
     *
     * @return
     */
    @GetMapping("/showpostil/{id}")
    public String showpostil(Integer id) {
        return "regulation/showpostil";
    }

    /**
     * 进入word详情页
     *
     * @return
     */
    @GetMapping("/showregulationhis/{ruleId}/{id}")
    public String showregulationhis(Integer ruleId, Integer id) {
        return "regulation/showregulationhis";
    }

    @PostMapping("/updaterule")
    @ResponseBody
    public ResultView updaterule(@RequestBody Rule rule) throws IOException {
        ResultView resultView = new ResultView(ResultView.SUCCESS);

        boolean bool = regulationService.updateRule(rule);

        if (!bool) {
            resultView.setStatus(ResultView.ERROR);
            resultView.setMsg("标题在所选目录中已存在");
            return resultView;
        }
        resultView.setStatus(ResultView.SUCCESS);
        return resultView;
    }

    @PostMapping("/coverfile")
    @ResponseBody
    public ResultView coverfile(@RequestBody Rule rule) throws IOException {
        ResultView resultView = new ResultView(ResultView.SUCCESS);

        Rule coverRule = regulationService.selectCoverRule(rule.getTitle(), rule.getCatalogId());

        rule.setId(coverRule.getId());
        boolean bool = regulationService.coverfile(rule);

        resultView.setStatus(ResultView.SUCCESS);
        return resultView;
    }

    @PostMapping("/deleterule")
    @ResponseBody
    public ResultView deleterule(@RequestBody Rule rule) throws IOException {
        ResultView resultView = new ResultView(ResultView.SUCCESS);

        regulationService.deleteRule(rule);
        return resultView;
    }

    @PostMapping("/inserthandrule")
    @ResponseBody
    public ResultView inserthandrule(@RequestBody Rule rule) throws IOException {

        ResultView resultView = new ResultView(ResultView.SUCCESS);
        rule.setRuleMenuId(11);
        regulationService.saveRule(rule);
        return resultView;
    }

    /**
     * 进入规章制度搜索页面
     *
     * @return
     */
    @GetMapping("/search")
    public String search() {

        return "regulation/search";
    }

    /**
     * 进入单文件上传页面
     *
     * @return
     */
    @GetMapping("/singlefile")
    public String singlefile() {
        return "regulation/singlefile";
    }

    @PostMapping("/regulationSel")
    @ResponseBody
    public ResultView regulationSel(@RequestBody Map<String, Object> condition) throws IOException {

        ResultView resultView = new ResultView(ResultView.SUCCESS);
        int pageNum = (int) condition.get("pageNum");

        String keyword = (String) (condition.get("keyword"));

        int from = (pageNum - 1) * 10;
        EsPage list = ElasticsearchUtils.searchDataPage("rules_and_regulations", "rule",
                from, 10, 0l, 0l, "", null, true, "content", "content=" + keyword);
        List resultList = list.getRecordList();

        PageInfo<Rule> searchRule = new PageInfo<>();

        Map map = new HashMap();
        List<Regulation> regulationList = regulationService.selectAllRegulations();
        if (regulationList != null && regulationList.size() > 0.) {
            for (int i = 0; i < regulationList.size(); i++) {
                Regulation rl = regulationList.get(i);
                map.put(String.valueOf(rl.getId()), rl.getUrl());
            }
        }
        if (resultList != null) {
            searchRule.setPageSize(10);
            searchRule.setPageNum(pageNum);
            List<Rule> ruleList = new ArrayList<>();
            for (int i = 0; i < resultList.size(); i++) {
                Map resultMap = (Map) resultList.get(i);
                Rule rule = new Rule();
                rule.setContent((String) resultMap.get("content"));
                rule.setTitle((String) resultMap.get("title"));
                rule.setId(Long.valueOf(resultMap.get("wordid").toString()));
                String parentUrl = (String) map.get(resultMap.get("rule_menu_id").toString());
                if (!StringUtils.isEmpty(parentUrl)) {
                    rule.setUrl(parentUrl);
                }

                ruleList.add(rule);
            }
            searchRule.setList(ruleList);
            searchRule.setTotal(list.getRecordCount());
        }

        resultView.setValue(searchRule);
        return resultView;
    }

    public static String htmlEncodeEscape(String source) {
        if (source == null) {
            return "";
        }
        String html = "";
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < source.length(); i++) {
            char c = source.charAt(i);
            switch (c) {
                case '<':
                    buffer.append("<");
                    break;
                case '>':
                    buffer.append(">");
                    break;
                case '&':
                    buffer.append("&");
                    break;
                case '"':
                    break;
                case 10:
                case 13:
                    break;
                default:
                    buffer.append(c);
            }
        }
        html = buffer.toString();
        return html;
    }

    public static String htmlEncode(String source) {
        if (source == null) {
            return "";
        }
        String html = "";
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < source.length(); i++) {
            char c = source.charAt(i);
            switch (c) {
                case '<':
                    buffer.append("&lt;");
                    break;
                case '>':
                    buffer.append("&gt;");
                    break;
                case '&':
                    buffer.append("&amp;");
                    break;
                case '"':
                    buffer.append("&quot;");
                    break;
                case 10:
                case 13:
                    break;
                default:
                    buffer.append(c);
            }
        }
        html = buffer.toString();
        return html;
    }

    /////
    // 将字符串中的换行符"\n"转换为html换行标记"&lt;br&gt;"
    //
    // param sSource 要替换的字符串。
    // return 返回替换后的字符串。
    ///
    public static String return2Br(String sSource) {
        return replace(sSource, "\n", "<br>");
    }

    /////
    // 将字符串中的空格" "转换为html的空格标记"&amp;nbsp;"
    //
    // param sSource 要替换的字符串。
    // return 返回替换后的字符串。
    ///
    public static String blank2NBSP(String sSource) {
        return replace(sSource, "\t", "&nbsp;&nbsp;");
    }
}
